package org.scratchcrew.services;

import org.scratchcrew.domain.User;
import org.scratchcrew.domain.dao.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Implementation of {@link UserService} interface.
 * 
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * User dao object used to access persistence.
	 */
	@Autowired
	private UserDao userDao;

	/**
	 * Support for digesting text. Used for passwords.
	 */
	@Autowired
	private DigestSupport digestSupport;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public User create(String userName, String password) {
		if (logger.isInfoEnabled()) {
			logger.info(String
					.format("Creating new user for name %s", userName));
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Digesting password");
		}
		String digestedPassword = digestSupport.digestToText(password);

		User user = new User();
		user.setUserName(userName);
		user.setPassword(digestedPassword);
		if (logger.isDebugEnabled()) {
			logger.debug("Saving user %s to database", user.getUserName());
		}
		userDao.save(user);
		return user;
	}

	@Override
	public void delete(Long id) {
		User user = userDao.find(id);
		userDao.delete(user);
	}

	@Override
	public User findByName(String userName){
		return userDao.findByName(userName);
	}
	
	@Override
	public User findByNameAndPass(String userName, String pass){
		User user = findByName(userName);
		if (user != null){
			String passDigest = digestSupport.digestToText(pass);
			if (user.getPassword().equals(passDigest)){
				return user;
			}
		}
		
		return null;
	}
	
	@Override
	public boolean exists(String userName){
		return userDao.findByName(userName) != null;
	}

	@Override
	public User find(Long id) {
		User user = userDao.find(id);
		return user;
	}
}
